'use strict';

/**
 * 字典项模型
 * @param app
 */
module.exports = app => {
  const { STRING, INTEGER, BOOLEAN, DATE, BIGINT } = app.Sequelize;

  const DictItem = app.model.define('sys_dict_items', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '字典项ID',
    },
    dictTypeId: {
      type: BIGINT,
      allowNull: false,
      comment: '字典类型ID',
      field: 'dict_type_id',
    },
    label: {
      type: STRING(50),
      allowNull: false,
      comment: '字典项标签',
    },
    value: {
      type: STRING(50),
      allowNull: false,
      comment: '字典项值',
    },
    sort: {
      type: INTEGER,
      allowNull: true,
      defaultValue: 0,
      comment: '排序号',
    },
    status: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '状态：true启用，false禁用',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
  });

  // 关联字典类型
  DictItem.associate = function() {
    app.model.DictItem.belongsTo(app.model.DictType,
      {
        foreignKey: 'dict_type_id',
        as: 'dictType',
      });
  };

  // 在创建前生成雪花ID
  DictItem.beforeCreate((dictItem) => {
    const SnowflakeUtil = require('../utils/snowflake');
    dictItem.id = SnowflakeUtil.generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  DictItem.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    // 移除重复的下划线字段
    delete values.create_time;
    delete values.update_time;
    delete values.dict_type_id;
    return values;
  };

  return DictItem;
};
